//
//  GradualView.swift
//  BasicProduct
//
//  Created by iOS on 2022/6/1.
//

import UIKit

open class ZLGradualView: UIView {
    
    public enum GradientPoint {
        case leftTop
        case leftBottom
        case rightTop
        case rightBottom
    }
    
    public var startPoint: GradientPoint = .leftTop {
        didSet {
            switch startPoint {
                case .leftTop:
                    gradualLayer.startPoint = CGPoint(x: 0, y: 0)
                case .leftBottom:
                    gradualLayer.startPoint = CGPoint(x: 0, y: 1)
                case .rightTop:
                    gradualLayer.startPoint = CGPoint(x: 1, y: 0)
                case .rightBottom:
                    gradualLayer.startPoint = CGPoint(x: 1, y: 1)
            }
        }
    }

    public var endPoint: GradientPoint = .leftTop {
        didSet {
            switch endPoint {
                case .leftTop:
                    gradualLayer.endPoint = CGPoint(x: 0, y: 0)
                case .leftBottom:
                    gradualLayer.endPoint = CGPoint(x: 0, y: 1)
                case .rightTop:
                    gradualLayer.endPoint = CGPoint(x: 1, y: 0)
                case .rightBottom:
                    gradualLayer.endPoint = CGPoint(x: 1, y: 1)
            }
        }
    }
    
    public var locations: [Float]? {
        didSet {
            var locations_ns: [NSNumber] = []
            for value in locations ?? [] {
                locations_ns.append(NSNumber(value: value))
            }
            gradualLayer.locations = locations_ns.count > 0 ? locations_ns : nil
        }
    }
    
    public var colors: [UIColor] = [] {
        didSet {
            var colors_cg: [CGColor] = []
            for color in colors {
                colors_cg.append(color.cgColor)
            }
            gradualLayer.colors = colors_cg
        }
    }
    
    public lazy var gradualLayer: CAGradientLayer = {
        let layer = CAGradientLayer()
        return layer
    }()
            
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubviews()
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    open override func layoutSubviews() {
        super.layoutSubviews()
        CATransaction.begin()
        CATransaction.setDisableActions(true)
        gradualLayer.frame = bounds
        CATransaction.commit()
    }
    
    private func addSubviews() {
        layer.addSublayer(gradualLayer)
    }
    
}

// 事件区
extension ZLGradualView {
    
    
    
}

// 定制区
extension ZLGradualView {
    
    
    
}
